package com.haralabidis.jdeveloper.extension.subversionmonitor.util.xml;

import java.io.IOException;
import java.io.InputStream;

import java.net.URL;

import java.util.HashSet;
import java.util.Set;

import oracle.ide.net.URLFactory;

import oracle.xml.parser.v2.DOMParser;
import oracle.xml.parser.v2.DTD;
import oracle.xml.parser.v2.XMLDocument;
import oracle.xml.parser.v2.XMLElement;
import oracle.xml.parser.v2.XMLParseException;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;


public class XMLExtractor {
    private DOMParser parser = null;
    private XMLDocument xmlDocument = null;

    public XMLExtractor(String filename, String dtdFile) {
        parser = new DOMParser();

        try {
            if (dtdFile != null && dtdFile.length() > 0) {
                InputStream isDTD =
                    XMLExtractor.class.getResourceAsStream("./jbo_03_01.jpg");
                parser.parseDTD(isDTD, "");
                DTD dtd = parser.getDoctype();
                parser.setDoctype(dtd);
            }
            parser.setValidationMode(false);
            URL url = URLFactory.newFileURL(filename);
            parser.parse(url);
            xmlDocument = parser.getDocument();
        } catch (XMLParseException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public XMLDocument getXMLDocument() {
        return this.xmlDocument;
    }

    public NodeList getNodes(String tag) {
        return this.xmlDocument.getElementsByTagName(tag);
    }

    public Set<String> extractChildren(String parent_tag, String child_tag) {

        Set<String> data = new HashSet();

        NodeList parent_nodes = getNodes(parent_tag);

        for (int i = 0; i < parent_nodes.getLength(); i++) {
            XMLElement parent_node = (XMLElement)parent_nodes.item(i);
            NodeList child_nodes =
                parent_node.getChildrenByTagName(child_tag);
            for (int j = 0; j < child_nodes.getLength(); j++) { 
                data.add(((XMLElement)child_nodes.item(j)).getText());
            }
        }
        
        return data;
    }

}
